import 'package:sqflite/sqflite.dart';

import '../bt_database_helper.dart';
import '../models/bt_order.dart';

class BtOrderProvider {
  late Database _db;

  BtOrderProvider._internal() {
    _db = DatabaseHelper().database;
  }

  factory BtOrderProvider() => _instance;

  static final BtOrderProvider _instance = BtOrderProvider._internal();

  Future<int> insert(BtOrder order) async {
    int id = await _db.insert(tableOrder, order.toMap());
    return id;
  }

  Future<BtOrder?> getOrder(String id) async {
    List<Map> maps = await _db.query(tableOrder,
        columns: [
          columnGoodsCode,
          columnGoodsName,
          columnOrderNo,
          columnPayAmount,
          columnPaidAmount,
          columnPaidCurrency
        ],
        where: '$columnOrderNo = ?',
        whereArgs: [id]);
    if (maps.isNotEmpty) {
      return BtOrder.fromMap(maps.first as Map<String, dynamic>);
    }
    return null;
  }

  Future<int> delete(String orderNo) async {
    return await _db.delete(tableOrder, where: '$columnOrderNo = ?', whereArgs: [orderNo]);
  }

  Future<int> deleteAll() async {
    return await _db.delete(tableOrder);
  }

  Future<int> update(BtOrder order) async {
    return await _db
        .update(tableOrder, order.toMap(), where: '$columnOrderNo = ?', whereArgs: [order.orderNo]);
  }

  Future<List<BtOrder>> queryAll() async {
    List<BtOrder> orders = [];
    List<Map<String, Object?>> records = await _db.query(tableOrder);
    for (var element in records) {
      orders.add(BtOrder.fromMap(element));
    }

    return orders;
  }
}
